package com.wondream.myframework.app.common.excel.function;

import com.wondream.myframework.app.common.excel.context.CfssPoiExporterContext;
import lombok.extern.slf4j.Slf4j;

import java.lang.reflect.Method;

/**
 * 函数注册器
 */
@Slf4j
public class FunctionRegister {

    /**
     * 注册函数
     */
    public static void registerInternalFunction(){
        final String op = "FunctionRegister.registerInternalFunction";
        Method[] declaredMethods = CfssExcelFunction.class.getDeclaredMethods();
        log.info(String.format("%s注册函数开始", op));
        for (Method method : declaredMethods) {
            CfssExcelFuncAnno annotation = method.getAnnotation(CfssExcelFuncAnno.class);
            if(null == annotation){
                continue;
            }
            log.info(String.format("%s注册函数 %s", op, annotation.value()));
            CfssPoiExporterContext.EVAL_CONTEXT.registerFunction(annotation.value(), method);
        }
        log.info(String.format("%s注册函数结束", op));
    }

    /**
     * 注册用户自定义函数
     */
    public static void registerCustomFunction(Class customCls){
        final String op = "FunctionRegister.registerCustomFunction";
        Method[] declaredMethods = customCls.getDeclaredMethods();
        log.info(String.format("%s注册用户自定义函数开始", op));
        for (Method method : declaredMethods) {
            if(method.getName().startsWith("cfss")){
                log.warn(String.format("%s注册用户自定义函数失败，不能注册cfss开头的函数:%s", op, method.getName()));
                continue;
            }
            CfssExcelFuncAnno annotation = method.getAnnotation(CfssExcelFuncAnno.class);
            log.info(String.format("%s注册用户自定义函数 %s", op, annotation.value()));
            CfssPoiExporterContext.EVAL_CONTEXT.registerFunction(annotation.value(), method);
        }
        log.info(String.format("%s注册用户自定义函数结束", op));
    }
}
